package com.xk.sport.backend.web.interceptor;

import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.xk.sport.backend.common.annotation.Auth;
import com.xk.sport.backend.common.annotation.Login;
import com.xk.sport.backend.common.constant.AdminRole;
import com.xk.sport.backend.common.constant.Constants;
import com.xk.sport.backend.common.constant.ResultStatus;
import com.xk.sport.backend.common.entity.Result;
import com.xk.sport.backend.common.util.CookieUtil;
import com.xk.sport.backend.common.util.DesUtil;
import com.xk.sport.backend.dao.model.Admin;
import com.xk.sport.backend.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class SecurityInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AdminService adminService;

    private Gson gson = new Gson();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        handlerAdminInfo(request);

        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        // TODO 暂时不做权限验证
        if (clazz.isAnnotationPresent(Login.class) || method.isAnnotationPresent(Login.class)) {// 需要登录验证
            Admin admin = (Admin) request.getAttribute(Constants.ADMIN_REQUEST_KEY);
            if (admin == null) {
                errorResult(response, new Result(ResultStatus.login_error.getStatus(), "未登录"));
                return false;
            }
            if (clazz.isAnnotationPresent(Auth.class) || method.isAnnotationPresent(Auth.class)) {// 需要权限
                int role = admin.getRole();
                if (role != AdminRole.system.getRole()) {
                    errorResult(response, new Result(ResultStatus.auth_error.getStatus(), "权限不够"));
                    return false;
                }
            }
        }
        return true;

    }

    private void errorResult(HttpServletResponse response, Result result) {
        try {
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(gson.toJson(result));
            out.flush();
            out.close();
        } catch (Exception e) {
        }
    }

    private void handlerAdminInfo(HttpServletRequest request) {
        String key = CookieUtil.getValue(request, Constants.ADMIN_CACHE_KEY);
        if (Strings.isNullOrEmpty(key)) {
            key = (String) request.getSession().getAttribute(Constants.ADMIN_CACHE_KEY);
        }
        if (!Strings.isNullOrEmpty(key)) {
            try {
                key = DesUtil.decrypt(key, DesUtil.key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String[] strs = key.split("_");
            Admin admin = adminService.findOneWithCache(Long.parseLong(strs[0]));
            if (admin == null) {
                return;
            }
            request.setAttribute(Constants.KEY_REQUEST_KEY, key);
            request.setAttribute(Constants.ADMIN_REQUEST_KEY, admin);
        }
    }
}
